package com.gitee.limaozhi.socket.lesson03.example4;

import com.gitee.limaozhi.socket.lesson03.example3.HandlerContext;
import com.gitee.limaozhi.socket.lesson03.example3.InputHandler;
import com.gitee.limaozhi.socket.lesson03.example3.OutputHandler;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * HTTP服务器
 *
 * @author hzlimaozhi
 * @date 2019/08/07 08:24
 */
public class HttpServer {

    private String localHost;
    private int localPort;
    private String name;

    private ExecutorService executorService;
    private ServerSocket serverSocket;

    private volatile boolean running = false;
    private volatile boolean stop = false;

    public HttpServer(String localHost, int localPort) {
        this.localHost = localHost;
        this.localPort = localPort;
        this.name = "HttpServer";
        this.executorService = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors());
    }

    public synchronized void start() {
        if (!running && !stop) {
            running = true;

            new Thread(() -> {
                try {
                    serverSocket = new ServerSocket();
                    serverSocket.bind(new InetSocketAddress(localHost, localPort));
                    System.out.println(name + "：启动");

                    int socketCount = 0;
                    while (!stop) {
                        Socket socket = serverSocket.accept();
                        String socketName = name + "-" + (++socketCount);
                        executorService.execute(() -> {
                            try {
                                HandlerContext context = new HandlerContext(socketName, socket, executorService);
                                context
                                        .addLast(new InputHandler())
                                        .addLast(new HttpDecoderHandler())
                                        .addLast(new HttpServerHandler())
                                        .addLast(new HttpEncoderHandler())
                                        .addLast(new OutputHandler())
                                        .start();
                            } catch (IOException e) {
                                e.printStackTrace();
                                try {
                                    socket.close();
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                }
                            }
                        });
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    close();
                }
            }).start();
        }
    }

    public synchronized void close() {
        if (!stop) {
            running = false;
            stop = true;

            if (serverSocket != null) {
                try {
                    executorService.shutdown();
                    serverSocket.close();
                    System.out.println(name + "：关闭");

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    executorService = null;
                    serverSocket = null;
                }
            }
        }
    }

    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 8000;
        new HttpServer(host, port).start();
    }

}
